package com.chaosj.skill.zipkin.filters

import com.chaosj.skill.zipkin.context.ApplicationContext

import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.FilterConfig
import javax.servlet.ServletException
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse

/**
 * @Description:
 * @author: caoyangjie
 * @date: 2019年12月2019/12/6日 09:21
 * @Copyright: © 赢时胜
 */
class TracerFilter implements Filter{

    static final String ZIP_KIN_SERVER = "zipKinServer"
    static final String LOCAL_SERVICE_NAME = "localServiceName"
    static final String SAMPLER = "sampler"

    @Override
    void init(FilterConfig filterConfig) throws ServletException {
        String zipKinServer = filterConfig.getInitParameter(ZIP_KIN_SERVER)
        String localServiceName = filterConfig.getInitParameter(LOCAL_SERVICE_NAME)
        String sampler = filterConfig.getInitParameter(SAMPLER)
        // 初始化 trace 链路相关上下文对象
        try{
            new ApplicationContext.Builder(
                    zipKinServer,
                    localServiceName,
                    Float.valueOf(sampler)
            ).initialization()
        }catch(Exception e){
            throw new ServletException(e.getMessage())
        }
    }

    @Override
    void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ApplicationContext.getBean(Filter.class).doFilter(servletRequest, servletResponse, filterChain)
    }
}
